package top.chukongxiang.project.base.oauth2.provider.cas;

import lombok.AllArgsConstructor;
import org.jasig.cas.client.proxy.ProxyGrantingTicketStorageImpl;
import org.jasig.cas.client.validation.Cas20ProxyTicketValidator;
import org.jasig.cas.client.validation.TicketValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.cas.ServiceProperties;
import org.springframework.security.cas.authentication.CasAuthenticationProvider;

/**
 * @author 楚孔响
 * @version 1.0
 * @date 2021/12/31 9:52
 */
@Configuration
@AllArgsConstructor
public class CasAuthenticationProviderConfigure {

    private final CasConfig casConfig;
    private final CasAuthenticationUserDetailsServiceImpl casAuthenticationUserDetailsServiceImpl;

    @Bean("pgtStorage")
    public ProxyGrantingTicketStorageImpl proxyGrantingTicketStorageImpl(){
        ProxyGrantingTicketStorageImpl proxyGrantingTicketStorage = new ProxyGrantingTicketStorageImpl();
        return proxyGrantingTicketStorage;
    }

    @Bean("casAuthenticationProvider")
    public CasAuthenticationProvider casAuthenticationProvider(){
        CasAuthenticationProvider authenticationProvider = new CasAuthenticationProvider();
        authenticationProvider.setKey("casProvider") ;
        // 此处不使用UserDetailService
        authenticationProvider.setAuthenticationUserDetailsService(casAuthenticationUserDetailsServiceImpl);
        authenticationProvider.setTicketValidator(ticketValidator());
        authenticationProvider.setServiceProperties(serviceProperties());
        return authenticationProvider;
    }

    @Bean
    public ServiceProperties serviceProperties(){
        ServiceProperties serviceProperties=new ServiceProperties();
        serviceProperties.setService(casConfig.getClient().getServiceUrl());
        serviceProperties.setAuthenticateAllArtifacts(true);
        return serviceProperties;
    }

    /**
     * cas2.0协议验证规范，由server端决定
     * @return
     */
    @Bean
    public TicketValidator ticketValidator() {
        Cas20ProxyTicketValidator ticketValidator = new Cas20ProxyTicketValidator(casConfig.getServer().getPrefixUrl());
        //允许所有代理回调链接
        ticketValidator.setAcceptAnyProxy(true);
        ticketValidator.setProxyGrantingTicketStorage(proxyGrantingTicketStorageImpl());
        return ticketValidator;
    }
}
